﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : Page
{
    private Dictionary<Guid, string> Names
    {
        get { return (Dictionary<Guid, string>) ViewState["Names"]; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            /*
             * to keep this sample really simple, we will populate some
             * sample data in a Dictionary and store in the viewstate
            */
            var names = new Dictionary<Guid, string>
                            {
                                {Guid.NewGuid(), "John"},
                                {Guid.NewGuid(), "Smith"},
                                {Guid.NewGuid(), "Arther"},
                                {Guid.NewGuid(), "Hari"}
                            };
            //store the list in the viewstate.
            ViewState.Add("Names", names);

            //init grid
            LoadNames();
        }
    }

    private void LoadNames()
    {
        //databind grid
        gvUsers.DataSource = ViewState["Names"];
        gvUsers.DataBind();
    }

    protected void btnAddSave_Click(object sender, EventArgs e)
    {
        Page.Validate("Add");

        if (Page.IsValid)
        {
            Names.Add(Guid.NewGuid(), txtNewName.Text);
            LoadNames();
            CloseDialog("newPerson");

            //reset
            txtNewName.Text = string.Empty;

            //refresh grid
            upGrid.Update();
        }
    }

    protected void btnEditSave_Click(object sender, EventArgs e)
    {
        Page.Validate("Edit");

        if (Page.IsValid)
        {
            Names[new Guid(txtEditId.Text)] = txtEditName.Text;
            LoadNames();
            CloseDialog("editPerson");

            //reset
            txtEditId.Text = string.Empty;
            txtEditName.Text = string.Empty;

            //refresh grid
            upGrid.Update();
        }
    }

    /// <summary>
    /// Populate the Dialog with the existing name
    /// and update the edit panel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbName_Click(object sender, EventArgs e)
    {
        var editLink = ((LinkButton) sender);
        txtEditId.Text = editLink.CommandArgument;
        txtEditName.Text = Names[new Guid(editLink.CommandArgument)];
        upEditUpdatePanel.Update();
    }


    /// <summary>
    /// Registers client script to close the dialog
    /// </summary>
    /// <param name="dialogId"></param>
    private void CloseDialog(string dialogId)
    {
        string script = string.Format(@"closeDialog('{0}')", dialogId);
        ScriptManager.RegisterClientScriptBlock(this, typeof (Page), UniqueID, script, true);
    }
}